﻿namespace IBTrader.Modules.Read
{
    using AxTWSLib;
    using IBTrader.Model;
    using System;
    using System.Linq;

    class ReaderSwitch : IReader
    {
        public IReader Reader { get; private set; }
        public event EventHandler<Line> Bid, Ask, Last, Volume, End;
        private readonly Model.Store store;
        private readonly int algoId;
        public ReaderSwitch(Store store, int algoId)
        {
            this.store = store;
            this.algoId = algoId;
        }
        public void Init(object _, EventArgs __)
        {
            var algo = store.Algos.SingleOrDefault(a => a.Id == algoId);
            if (algo == null) return;
            algo.BacklogConfiguration.PropertyChanged += (___, e) => 
            {
                if (e.PropertyName == "FileFormat")
                {
                    var type = algo.BacklogConfiguration.FileFormats.Single(f => f.Value == algo.BacklogConfiguration.FileFormat).Type;
                    if (Reader == null || (Reader.GetType() != typeof(ReaderRealTime) && Reader.GetType() != type))
                        Switch(type);
                }
            };
        }
        public bool Do(IReaderConfiguration configuration)
        {
            return Reader != null ? Reader.Do(configuration) : false;
        }
        public void Read(object o, _DTwsEvents_tickPriceEvent e)
        {
            if (Reader != null) Reader.Read(o, e);
        }
        public void Read(object o, _DTwsEvents_tickSizeEvent e)
        {
            if (Reader != null) Reader.Read(o, e);
        }
        public void Cancel(object o, EventArgs e)
        {
            if (Reader != null) Reader.Cancel(o, e);
        }
        internal void Switch(Type type)
        {
            if (Reader != null)
            {
                Reader.Bid -= Bid;
                Reader.Ask -= Ask;
                Reader.Last -= Last;
                Reader.Volume -= Volume;
                Reader.End -= End;
            }

            Reader = Activator.CreateInstance(type) as IReader;
            Reader.Bid += Bid;
            Reader.Ask += Ask;
            Reader.Last += Last;
            Reader.Volume += Volume;
            Reader.End += End;
        }
    }
}
